#include "mainwindow.h"
#include "ui_mainwindow.h"

#include "grammar/util.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->butonDoIt, SIGNAL(clicked()), this, SLOT(onDoIt()));
    connect(ui->buttonBrowseSave, SIGNAL(clicked()), this, SLOT(onBrowseSave()));

    ui->butonDoIt->setShortcut(QKeySequence("Return"));

}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::changeEvent(QEvent *e)
{
    QMainWindow::changeEvent(e);
    switch (e->type()) {
    case QEvent::LanguageChange:
        ui->retranslateUi(this);
        break;
    default:
        break;
    }
}

void MainWindow::keyPressEvent(QKeyEvent *e)
{
    if(e->key() == Qt::Key_Escape){
        this->close();
    }
}

void MainWindow::onBrowseSave()
{
    QString path = QFileDialog::getSaveFileName(this, "Save...", QDir::homePath(),  tr("XMI files (*.umi *.xmi)"));
    if(!path.isEmpty())
        ui->editSaveFile->setText(path);
}

void MainWindow::onDoIt()
{

    // TODO cały stuff zwiazany z wywolywaniem parsera i budowaniem drzewa

    QMap<QString,Clazz*> *tree;

    if( (tree = xxx("testFile") ) == NULL){
        QMessageBox::warning(this, "Error", "File not found");
        return;
    }

    XMLSerializable::currentNumber = 3;
    Model* model = Model::getInstance(tree);

    // TODO dodac warunek na katalogi wejsciowe
    QString outPath = ui->editSaveFile->text();

    if(!outPath.isEmpty()){
        QFile file(outPath);
        if(!file.open(QFile::WriteOnly))
        {
            QMessageBox::warning(this, "Error", "Error during opening file "+outPath+"\n"+file.errorString());
            return;
        }

        file.write(model->toXml().toUtf8());

        file.close();

        QMessageBox::information(this, "Done", "Successfully done!");
    }
}
